package com.bawei.ivideo.test.mvi

import androidx.lifecycle.viewModelScope
import com.bawei.ivideo.test.mvi.http.VideoEntity
import com.bawei.library_mvi.model.BaseViewModel
import com.bawei.library_net.entity.ResponseEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 * @Author : yaotianxue
 * @Time : On 2023/6/19 16:40
 * @Description : TestViewModel
 */
class TestViewModel:BaseViewModel<TestIntent>() {
    val service: TestService by lazy { TestService() }//网络请求数据服务



    private val _state = MutableStateFlow<TestUIState>(TestUIState.Init)//必须放一个初始状态
    val state:StateFlow<TestUIState>
        get() = _state


    //处理用户的intent意图：通过通道
    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect{
                //判断请求类型获得对应的数据
                when(it){
                    is TestIntent.MultiVideoIntent -> getMultiVideoData(it) //it包含参数
                }
            }
        }

    }

    private fun getMultiVideoData(intent: TestIntent.MultiVideoIntent) {
        viewModelScope.launch {
            flow {
                val multiVideo = service.multiVideo(intent.page, intent.pagesize)
                emit(multiVideo)
            }.flowOn(Dispatchers.Default)
                .catch { exception->
                    //失败状态
                    _state.value = TestUIState.Error(exception)
                }.collect{
                    if( it.data.isNullOrEmpty() || it.data.equals("")){
                        //空状态
                        _state.value = TestUIState.Empty
                    }else{
                        //成功
                        _state.value = TestUIState.MultiVideoState(it.data)
                    }

                }

        }
    }






}